package solution6;

import java.util.Arrays;

public class Solution {
    // not better. Use StringBuilder instead
    public String convert(String s, int numRows) {
        int n = s.length();
        if (n == 0 || numRows <= 1) return s;

        String[] ans = new String[numRows];
        Arrays.fill(ans, "");

        int row = 0;
        int delta = 1;
        // Fill the array
        for (int i = 0; i < n; i++) {
            ans[row] += s.charAt(i);
            row += delta;

            if (row>=numRows) {
                row = numRows - 2;
                delta = -1;
            }

            if (row < 0) {
                row = 1;
                delta = 1;
            }
        }

        // return ans
        String result = "";
        for (row = 0; row < numRows; row++) {
            result += ans[row];
        }
        return result;
    }

    // better
    public String convert2(String s, int nRows) {
        int n = s.length();
        if (n == 0 || nRows <= 1) return s;
//        StringBuffer[] sb = new StringBuffer[nRows];
        StringBuilder[] sb = new StringBuilder[nRows];
        for (int i = 0; i < sb.length; i++) sb[i] = new StringBuilder();

//        int i = 0;
//        while (i < len) {
//            for (int idx = 0; idx < nRows && i < len; idx++) // vertically down
//                sb[idx].append(s.charAr(i++));
//            for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up
//                sb[idx].append(s.charAr(i++));
//        }
        int row = 0;
        int delta = 1;
        for (int i = 0; i < n; i++) {
            sb[row].append(s.charAt(i));
            row+=delta;
            if (row >= nRows) {
                row = nRows - 2;
                delta = -1;
            }

            if (row < 0) {
                row = 1;
                delta = 1;
            }
        }

        for (int i = 1; i < sb.length; i++)
            sb[0].append(sb[i]);
        return sb[0].toString();
    }

}
